﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using PCSComUtils.Admin.BO;
using PCSComUtils.Common;
using PCSComUtils.DataAccess;
using PCSUtils.Utils;

namespace PCSUtils.Admin
{
    public partial class UpdatePassword : Form
    {
        public UpdatePassword()
        {
            InitializeComponent();
        }

        private void btnSave_Click(object sender, EventArgs e)
        {
            if (ChangePassword())
            {
                PCSMessageBox.Show(ErrorCode.PASSWORD_UPDATE_SUCCESSFUL);
                // reset form
                txtOldPassword.Text = txtNewPassword.Text = txtConfirmPassword.Text = string.Empty;
            }
        }

        private bool ChangePassword()
        {
            if (string.IsNullOrEmpty(txtOldPassword.Text))
            {
                PCSMessageBox.Show(ErrorCode.MANDATORY_INVALID);
                txtOldPassword.Focus();
                return false;
            }
            if (string.IsNullOrEmpty(txtNewPassword.Text))
            {
                PCSMessageBox.Show(ErrorCode.MANDATORY_INVALID);
                txtOldPassword.Focus();
                return false;
            }
            if (string.IsNullOrEmpty(txtConfirmPassword.Text))
            {
                PCSMessageBox.Show(ErrorCode.MANDATORY_INVALID);
                txtOldPassword.Focus();
                return false;
            }

            var oldPassword = txtOldPassword.Text.Trim();
            var newPassword = txtNewPassword.Text.Trim();
            var confirmPassword = txtConfirmPassword.Text.Trim();

            // newPassword must match with confirmPassword
            if (!newPassword.Equals(confirmPassword, StringComparison.InvariantCulture))
            {
                PCSMessageBox.Show(ErrorCode.NEWPASSWORD_DIFFERENT_CONFIRMPASSWORD);
                txtNewPassword.Focus();
                return false;
            }

            // validate old password
            var encryptedPwd = CryptoUtil.EncryptPassword(oldPassword);
            var managerUserBo = new ManageUserBO();
            var isValidPwd = managerUserBo.ValidateUser(SystemProperty.UserName, encryptedPwd);
            if (!isValidPwd)
            {
                PCSMessageBox.Show(ErrorCode.INVALID_PASSWORD);
                txtOldPassword.Focus();
                return false;
            }

            managerUserBo.UpdatePassword(SystemProperty.UserName, encryptedPwd, CryptoUtil.EncryptPassword(newPassword));
            return true;
        }

        private void btnClose_Click(object sender, EventArgs e)
        {
            Close();
        }
    }
}
